package com.library.admin.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.library.common.constant.CacheTimeConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Jwt生成Token工具类
 * JWT token的格式：header.payload.signature
 *
 * @author: xyh
 * @create: 2023-04-16
 **/
@Log4j2
@Component
public class JwtTokenUtil {

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    private static final int REFRESH_TIME = 30 * 60;

    @Value("${jwt.key}")
    private String key;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    /**
     * 用户登录成功后生成Jwt的token,使用HS512算法
     *
     * @param userDetails
     * @return token
     */
    public String createJwtToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims, userDetails.getUsername());
    }

    /**
     * 根据负责生成JWT的token
     *
     * @param claims
     * @param username
     * @return
     */
    private String generateToken(Map<String, Object> claims, String username) {
        JwtBuilder builder = Jwts.builder()
                .addClaims(claims)
                .setIssuedAt(new Date())
                .setSubject(username)
                //设置过期时间，一小时后过期
                .setExpiration(new Date(System.currentTimeMillis() + CacheTimeConstant.tokenExpiration))
                //设置签名使用的签名算法和签名使用的秘钥
                .signWith(SignatureAlgorithm.HS512, key);
        return builder.compact();
    }

    /**
     * token验证
     *
     * @param token 加密后的token
     * @return
     */
    private Claims parseJWT(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("token：{}，格式验证失败！错误信息为: ", token, e);
        }
        return claims;
    }

    /**
     * 验证token是否有效
     *
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     * @return true:有效
     */
    public Boolean isVerifyToken(String token, UserDetails userDetails) {
        Claims claims = parseJWT(token);
        Date expiration = claims.getExpiration();
        String username = claims.getSubject();
        if (StrUtil.isNotEmpty(username)) {
            if (username.equals(userDetails.getUsername()) && expiration.after(new Date())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = parseJWT(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
            log.error("token：{}，根据token获取用户名失败！错误信息为: ", token, e);
        }
        return username;
    }

    /**
     * 当原来的token没过期时是可以刷新的
     *
     * @param oldToken 带tokenHead的token
     */
    public String refreshHeadToken(String oldToken) {
        if (StrUtil.isEmpty(oldToken)) {
            return null;
        }
        String token = oldToken.substring(tokenHead.length());
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        //token校验不通过
        Claims claims = parseJWT(token);
        if (claims == null) {
            return null;
        }
        //如果token已经过期，不支持刷新
        if (claims.getExpiration().before(new Date())) {
            return null;
        }
        //如果token在30分钟之内刚刷新过，返回原token

        if (tokenRefreshJustBefore(token, REFRESH_TIME)) {
            return token;
        } else {
            claims.put(CLAIM_KEY_CREATED, new Date());
            return generateToken(claims, getUserNameFromToken(token));
        }
    }

    /**
     * 判断token在指定时间内是否刚刚刷新过
     *
     * @param token 原token
     * @param time  指定时间（秒）
     */
    private boolean tokenRefreshJustBefore(String token, int time) {
        Claims claims = parseJWT(token);
        Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
        Date refreshDate = new Date();
        //刷新时间在创建时间的指定时间内
        if (refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, time))) {
            return true;
        }
        return false;
    }

}
